<?php
require_once __DIR__ . '/Workerman/Autoloader.php';
require_once __DIR__ . '/Workerman/Mysql/Connection.php';

use Workerman\Worker;

global $db,$rooms,$config;
$config = require_once __DIR__ . '/Application/Common/Conf/config.php';
if(is_cli()){
	// $context = array(
	//     'ssl' => array(
	//         // 请使用绝对路径
	//         'local_cert'  => '/www/cert/1_socket.58zltc.com_bundle.crt', // 也可以是crt文件
	//         'local_pk'    => '/www/cert/2_socket.58zltc.com.key',
	//         'verify_peer' => false,
	//     )
	// );
	// var_dump($config);
	// 这里设置的是websocket协议（端口任意，但是需要保证没被其它程序占用）
	// $worker = new Worker('websocket://0.0.0.0:4432', $context);
	$worker = new Worker('websocket://0.0.0.0:4432');
	// 设置transport开启ssl，websocket+ssl即wss
	// $worker->transport = 'ssl';

	$worker->onWorkerStart = function($worker){
	    // 将db实例存储在全局变量中(也可以存储在某类的静态成员中)
	    global $db,$config;
	    $db = new \Workerman\MySQL\Connection($config['DB_HOST'], $config['DB_PORT'], $config['DB_USER'], $config['DB_PWD'], $config['DB_NAME']);
	};
	$worker->onMessage = function($con, $msg) {
		$data = json_decode($msg, 1);
		switch ($data['type']) {
			case 'join':
				$res = joinZhibo($con, $data);
				break;
			case 'reply':
				$res = reply($con, $data);
				break;
			case 'zhibo':
				$res = gift($con, $data);
				break;
			case 'ping':
				var_dump($data);
				$arr['type'] = 'pong';
				$arr = json_encode($arr);
				$con->send($arr);
				break;
			
			default:
				# code...
				break;
		}
	};

	Worker::runAll();
}else{
	exit("你访问的页面不存在！");
}


// 加入房间
function joinZhibo($con, $data){
	global $db,$rooms;

	$rooms[$data['id']][$data['openid']] = $con;
	$map['id'] = $data['id'];

	$info = $db->select('*')->from('tp_zhibo')->where('id= :id')->bindValues($map)->row();
	if(!$info){
		return false;
	}
	$eq['wid'] = $info['wid'];
	$eq['id'] = $info['goods'];
	$info['goods_list'] = $db->select('*')->from('tp_goods')->where('wid= :wid AND id in (:id)')->bindValues($eq)->query();

	$eq1['wid'] = $info['wid'];
	$eq1['mid'] = $info['member_id'];
	$info['member'] = $db->select('*')->from('tp_member')->where('wid= :wid AND mid= :mid')->bindValues($eq1)->row();

	$eq3['type'] = 'zhibo';
	$eq3['to'] = $info['member']['openid'];
	$eq3['is_pay'] = 1;
	$info['gift_num'] = $db->select('COUNT(*)')->from('tp_quan_gift_order')->where('`type`= :type AND `to`= :to AND `is_pay`= :is_pay')->bindValues($eq3)->single();
	$info['order_num'] = 0;
	$info['member_num'] = count($rooms[$data['id']]);

	$eq4['openid'] = $data['openid'];
	$eq4['follow_openid'] = $info['member']['openid'];
	$info['is_follow'] = $db->select('id')->from('tp_quan_follow')->where('follow_openid= :follow_openid AND openid= :openid')->bindValues($eq4)->single();

	$eq5['type'] = 'zhibo';
	$eq5['qid'] = $data['id'];
    $eq5['openid'] = $data['openid'];
    $info['is_zan'] = $db->select('id')->from('tp_quan_zan_log')->where('type= :type AND qid= :qid AND openid= :openid')->bindValues($eq5)->single();

	$res['data'] = $info;
	$res['type'] = 'info';
	$res = json_encode($res);
	$con->send($res);

	$eq2['openid'] = $data['openid'];
	$member = $db->select('*')->from('tp_member')->where('openid= :openid')->bindValues($eq2)->row();
	$new['type'] = 'join';
	$new['data'] = $member['nickname'];
	$new = json_encode($new);
	foreach ($rooms[$data['id']] as $k => $v) {
		$v->send($new);
	}
} 
// 评论
function reply($con, $data){
	global $db,$rooms;

	$eq2['openid'] = $data['openid'];
	$member = $db->select('*')->from('tp_member')->where('openid= :openid')->bindValues($eq2)->row();

	$new['type'] = 'reply';
	$new['data']['nickname'] = $member['nickname'];
	$new['data']['content'] = $data['content'];
	$new = json_encode($new);
	foreach ($rooms[$data['id']] as $k => $v) {
		$v->send($new);
	}
}
// 送礼物
function gift($con, $data){
	global $db,$rooms;

	$eq['form'] = $data['from'];
	$eq['to'] = $data['to'];
	$eq['gift_id'] = $data['gift_id'];
	if(!$db->select('*')->from('tp_quan_gift_order')->where('form= :form AND to= :to AND gift_id= :gift_id')->bindValues($eq)->orderByDESC(array('last_time'))->row()){
		return fasle;
	}
	$eq1['gift_id'] = $data['gift_id'];

	$eq2['openid'] = $data['from'];
	$member = $db->select('*')->from('tp_member')->where('openid= :openid')->bindValues($eq2)->row();
	$new['type'] = 'gift';
	$new['data']['nickname'] = $member['nickname'];
	$new['data']['icon'] = $db->select('icon')->from('tp_quan_zan_log')->where('gift_id= :gift_id')->bindValues($eq1)->single();
	$new = json_encode($new);
	// var_dump($rooms[$data['id']]);
	foreach ($rooms[$data['id']] as $k => $v) {
		$v->send($new);
	}
}

function is_cli(){
	return preg_match("/cli/i", php_sapi_name()) ? true : false;
}